package com.algorithm.binarysearch;

public class BinarySearchNoRecur {
    public static void main(String[] args) {
        int arr[] = {1,3,8,10,34,36};
        System.out.println(binarySearch(arr, 1));
    }


    /**
     * 二分查找的非递归实现，如果没有找到返回-1
     * @param arr 待查找的有序数组
     * @param findVal 需要查找的数
     */
    public static int binarySearch(int[] arr,int findVal){
        int left = 0;
        int right = arr.length-1;
        while(left <= right){
            int mid = (left+right)/2;
            if(arr[mid] == findVal){
                return mid;
            }else if(arr[mid] > findVal){
                right = mid - 1;
            }else {
                left = left + 1;
            }
        }
        return -1;
    }
}
